package pw.hais.dadishu.activitys;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.SaveCallback;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import pw.hais.dadishu.R;
import pw.hais.dadishu.adapters.GameLoveAdapter;
import pw.hais.dadishu.app.BaseActivity;
import pw.hais.dadishu.dao.RanKingDao;
import pw.hais.dadishu.entitys.GameScenarioInfo;
import pw.hais.dadishu.helpers.AudioHelper;
import pw.hais.dadishu.ui.GameFailedPopupWindow;
import pw.hais.dadishu.ui.GameWinPopupWindow;
import pw.hais.utils.DownTime;
import pw.hais.utils.L;
import pw.hais.utils.SPUtils;

/**
 * 开始正常模式游戏
 * Created by HaiSheng on 2015/7/4.
 */
public class PlayNormalGameActivity extends BaseActivity implements View.OnClickListener {
    public static final String SP_GAME_Normal_SCENARION_INFO_KEY = "GAME_Normal_SCENARION_INFO_KEY";      //存储当前游戏信息
    private GameScenarioInfo gameScenarioInfo;      //游戏场景信息
    private boolean gameState = false;      //游戏状态
    private int startDownTime = 3;     //开始倒计时

    private List<ImageView> dishu_list = new ArrayList<>(); //所有地鼠
    private TranslateAnimation animation_dishu_up, animation_dishu_down;    //地鼠 出入洞，动画
    private TextView text_nowResults, text_nowScenarion, text_WinNum;      //actionbar？
    private TextView text_downTime;
    private GridView gridView_love;             //生命值View
    private GameLoveAdapter gameLoveAdapter;    //生命值Adapter

    private Drawable drawable_dishu_yun;       //被打中的地鼠图片
    private DownTime gameDownTime;              //游戏倒计时 时间

    private GameFailedPopupWindow gameFailedPopupWindow;        //失败框
    private GameWinPopupWindow gameWinPopupWindow;              //胜利

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_normal_game);

        initGameData();     //初始化游戏数据
        initLayout();       //初始化视图
        initDishuAnimation();   //初始化动画
        refreshDataToView();    //刷新视图UI

        //开始倒计时
        new DownTime((startDownTime+1) * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                text_downTime.setText(startDownTime + "");
                startDownTime--;
            }
            @Override
            public void onFinish() {
                text_downTime.setVisibility(View.GONE);
                startGame();    //开始游戏
            }
        }.start();
    }

    /**
     * 初始化游戏数据
     */
    private void initGameData() {
        gameScenarioInfo = SPUtils.getObject(SP_GAME_Normal_SCENARION_INFO_KEY, GameScenarioInfo.class, null);
        if (gameScenarioInfo == null) { //第一关
            gameScenarioInfo = new GameScenarioInfo();
            gameScenarioInfo.scenarioDiSuStopTime = 1 * 1000;       //关卡地鼠停止时间,秒
            gameScenarioInfo.scenarioOneSecUpNum = 1 * 1000;            //关卡地鼠出现的间隔
            gameScenarioInfo.scenarioWinGameNum = 10;                        //关卡胜利条件
            gameScenarioInfo.scenarioDiShuOutNum = 10;                         //地鼠死亡获得的分数
            gameScenarioInfo.scenarioBackground = R.drawable.background;      //关卡背景图片
            gameScenarioInfo.nowScenarion = 1;   //当前关卡
            gameScenarioInfo.nowResults = 0;     //当前分数
            gameScenarioInfo.nowlife = 1;        //当前生命
        }
        gameScenarioInfo.nowWinGameNum = gameScenarioInfo.scenarioWinGameNum;       //胜利所需要打的地鼠
    }

    /**
     * 初始化视图
     */
    private void initLayout() {
        text_nowResults = findView(R.id.text_nowResults);
        text_nowScenarion = findView(R.id.text_nowScenarion);
        text_WinNum = findView(R.id.text_WinNum);
        text_downTime = findView(R.id.text_downTime);
        text_downTime.setVisibility(View.VISIBLE);

        gameLoveAdapter = new GameLoveAdapter(gameScenarioInfo.nowlife);
        gridView_love = findView(R.id.listView_love);
        gridView_love.setAdapter(gameLoveAdapter);
        findViewAndSetOnClick(R.id.btn_buy);
        gridView_love.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //gameScenarioInfo.nowlife--;
                //gameLoveAdapter.setLoveNum(gameScenarioInfo.nowlife);
                L.showShort("功能开发中....");
                AudioHelper.playSound(AudioHelper.DI_SHU_UP, 0);
            }
        });

        //初始化地鼠
        initDiShuAddList((ImageView) findViewById(R.id.img_dishu_1));
        initDiShuAddList((ImageView) findViewById(R.id.img_dishu_2));
        initDiShuAddList((ImageView) findViewById(R.id.img_dishu_3));
        initDiShuAddList((ImageView) findViewById(R.id.img_dishu_4));
        initDiShuAddList((ImageView) findViewById(R.id.img_dishu_5));
        initDiShuAddList((ImageView) findViewById(R.id.img_dishu_6));
        initDiShuAddList((ImageView) findViewById(R.id.img_dishu_7));
        initDiShuAddList((ImageView) findViewById(R.id.img_dishu_8));

        drawable_dishu_yun = getResources().getDrawable(R.drawable.dishu_yun);

        //失败弹窗
        gameFailedPopupWindow = new GameFailedPopupWindow(this) {
            @Override
            public void onClick(View view) {
                switch (view.getId()){
                    case R.id.btn_return:
                        finish();
                        break;
                    case R.id.btn_ranking:
                        startActivity(new Intent(context,RankingActivity.class));
                        break;
                }
            }
        };

        //成功弹窗
        gameWinPopupWindow = new GameWinPopupWindow(this) {
            @Override
            public void onClick(View view) {
                switch (view.getId()){
                    case R.id.btn_return:
                        finish();
                        break;
                    case R.id.btn_next:
                        view.setEnabled(false); //只能点击一次
                        gameScenarioInfo.scenarioDiSuStopTime -= gameScenarioInfo.scenarioDiSuStopTime/50;       //关卡地鼠停止时间,秒
                        gameScenarioInfo.scenarioOneSecUpNum -= gameScenarioInfo.scenarioOneSecUpNum/15;        //关卡地鼠出现的间隔
                        gameScenarioInfo.scenarioWinGameNum += 2;          //关卡胜利条件
                        gameScenarioInfo.scenarioDiShuOutNum += 0;          //地鼠死亡获得的分数
                        gameScenarioInfo.scenarioBackground = R.drawable.background;   //关卡背景图片
                        gameScenarioInfo.nowScenarion += 1;   //当前关卡
                        gameScenarioInfo.nowlife +=1;       //生命加1

                        SPUtils.saveObject(SP_GAME_Normal_SCENARION_INFO_KEY, gameScenarioInfo);
                        startActivity(new Intent(context,PlayNormalGameActivity.class));
                        finish();
                        break;
                }
            }
        };

    }

    /**
     * 初始化地鼠
     */
    public void initDiShuAddList(final ImageView dishu) {
        dishu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (dishu.getVisibility() == View.VISIBLE && dishu.getDrawable() != drawable_dishu_yun) {
                    AudioHelper.playSound(AudioHelper.DI_SHU_CLICK, 0);
                    dishu.setImageDrawable(drawable_dishu_yun);
                    //地鼠死亡分数
                    gameScenarioInfo.nowResults += gameScenarioInfo.scenarioDiShuOutNum;
                    gameScenarioInfo.nowWinGameNum--;
                    refreshDataToView();
                }
            }
        });

        dishu.setVisibility(View.GONE);
        dishu_list.add(dishu);
    }

    /**
     * 初始化地鼠 出入 动画
     */
    private void initDishuAnimation() {
        animation_dishu_up = new TranslateAnimation(0, 0, 140, 0);
        animation_dishu_up.setDuration(gameScenarioInfo.scenarioDiSuStopTime / 4);
        animation_dishu_up.setRepeatMode(Animation.ZORDER_TOP);//设置方向

        animation_dishu_down = new TranslateAnimation(0, 0, 0, 140);
        animation_dishu_down.setDuration(gameScenarioInfo.scenarioDiSuStopTime / 4);
        animation_dishu_down.setRepeatMode(Animation.ZORDER_TOP);//设置方向
    }

    /**
     * 开始游戏
     */
    private void startGame() {
        gameState = true;   //开始游戏
        gameDownTime = new DownTime(Long.MAX_VALUE, gameScenarioInfo.scenarioOneSecUpNum) {
            @Override
            public void onTick(long millisUntilFinished) {
                if(gameState){
                    ImageView dishu = dishu_list.get(get1To8Random() - 1); //获取当前地鼠
                    if (dishu.getVisibility() != View.VISIBLE) {
                        showDiShu(dishu);   //显示地鼠动画
                    }
                }else{
                    onFinish();
                }
            }

            @Override
            public void onFinish() {
                cancel();
            }
        }.start();

    }

    /**
     * 显示地鼠
     */
    private void showDiShu(final ImageView dishu) {
        //显示地鼠
        dishu.setVisibility(View.VISIBLE);
        dishu.startAnimation(animation_dishu_up);

        //延迟N秒后 收回地鼠
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                dishu.startAnimation(animation_dishu_down);
                animation_dishu_down.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        hideDiShu(dishu);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                    }
                });
            }
        }, gameScenarioInfo.scenarioDiSuStopTime);
    }

    /**
     * 隐藏地鼠
     */
    private void hideDiShu(ImageView dishu) {
        if(gameState){
            if (dishu.getDrawable() != drawable_dishu_yun) {
                AudioHelper.playSound(AudioHelper.DI_SHU_PAO,0);    //跑
                gameScenarioInfo.nowlife--;
                refreshDataToView();
                if (gameScenarioInfo.nowlife == 0) {    //结束游戏
                    gameState = false;
                    AudioHelper.playSound(AudioHelper.DI_SHU_FAILED, 0);
                    gameDownTime.onFinish();

                    //提交游戏分数
                    int results = SPUtils.getObject("user.nowResults", Integer.class,0);
                    if(results < gameScenarioInfo.nowResults) {
                        loadDialog.show("正在提交结果到服务器！");
                        SPUtils.saveObject("user.nowResults", gameScenarioInfo.nowResults);    //存入分数到本地。
                        //根据用户名查询，当前最高成绩
                        RanKingDao.deleteUserInfo(new FindCallback<AVObject>() {
                            @Override
                            public void done(List<AVObject> list, AVException e) {
                                loadDialog.dismiss();
                                RanKingDao.updateUserInfo(gameScenarioInfo);
                            }
                        });

                    }
                    //显示失败弹窗
                    gameFailedPopupWindow.setText_msg("游戏失败\n　　还需要打"+gameScenarioInfo.nowWinGameNum+"只地鼠才能胜利，请继续努力！");
                    gameFailedPopupWindow.showCenter();
                    return;
                }
            } else {
                if (gameScenarioInfo.nowWinGameNum <= 0 ) {
                    gameState = false;
                    AudioHelper.playSound(AudioHelper.DI_SHU_WIN,0);
                    gameWinPopupWindow.setText_msg("游戏胜利\n　　进入下一局后，自动保存进度。");
                    gameWinPopupWindow.showCenter();
                    gameDownTime.onFinish();
                    return;
                }
            }
            dishu.setVisibility(View.GONE);
            dishu.setImageResource(R.drawable.dishu);
        }else{
            gameDownTime.onFinish();
        }

    }


    /**
     * 刷新数据
     */
    private void refreshDataToView() {
        text_nowResults.setText("总分:" + gameScenarioInfo.nowResults);
        text_nowScenarion.setText("第" + gameScenarioInfo.nowScenarion + "关");
        text_WinNum.setText("" + gameScenarioInfo.nowWinGameNum);
        gameLoveAdapter.setLoveNum(gameScenarioInfo.nowlife);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_buy:
                L.showShort("功能正在开发中...");
                break;
        }
    }


    /**
     * 获取 1-8 随机数
     *
     * @return
     */
    public int get1To8Random() {
        int max = 8;
        int min = 1;
        Random random = new Random();
        return random.nextInt(max) % (max - min + 1) + min;
    }
}
